package com.lakeworks.framework.config;

import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @Author: Auxps
 * @Date: 2023/7/1
 * Description:
 */
@Configuration
@EnableCaching
@EnableConfigurationProperties(CacheProperties.class)
public class RedisCacheConfig {

    @Bean
    RedisCacheConfiguration redisCacheConfiguration(CacheProperties cacheProperties) {
        RedisCacheConfiguration configuration = RedisCacheConfiguration.defaultCacheConfig()
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));

        CacheProperties.Redis redisProperties = cacheProperties.getRedis();

        //ttl
        if (redisProperties.getTimeToLive() != null)
            configuration = configuration.entryTtl(redisProperties.getTimeToLive());

        //key前缀  如果指定了前缀 就用指定的前缀  没有 则默认使用缓存的名字作为前缀
        if (redisProperties.getKeyPrefix() != null)
            configuration = configuration.prefixCacheNameWith(redisProperties.getKeyPrefix());

        //缓存空值  防止缓存穿透
        if (!redisProperties.isCacheNullValues())
            configuration = configuration.disableCachingNullValues();

        //是否使用前缀  false 禁用
        if (!redisProperties.isUseKeyPrefix())
            configuration = configuration.disableKeyPrefix();

        return configuration;
    }
}
